package com.dhcc.immutable;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @ClassName: Immutable_01
 * @Description: 创建不可变的集合
 * @author weiyongpeng
 * @date 2023年5月7日 上午8:12:20
 */
public class Immutable_01 {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		/*
		 * 
		 * 创建不可变的List集合
		 * 
		 * "张三", "李四", "王五", "赵六"
		 * 
		 */

		// 一旦创建完毕之后，是无法进行修改的，在下面的代码中，只能进行查询操作
		// List.of();这个方法只有在jdk8之后才有
		List<String> list = Arrays.asList("张三", "李四", "王五", "赵六");

		System.out.println(list.get(0));

		System.out.println(list.get(1));

		System.out.println(list.get(2));

		System.out.println(list.get(3));

		System.out.println("---------------------------");

		for (String s : list) {

			System.out.println(s);

		}

		System.out.println("---------------------------");

		Iterator<String> it = list.iterator();

		while (it.hasNext()) {

			String s = it.next();

			System.out.println(s);

		}

		System.out.println("---------------------------");

		for (int i = 0; i < list.size(); i++) {

			String s = list.get(i);

			System.out.println(s);

		}

		System.out.println("---------------------------");

		// list.remove("李四");

		// list.add("aaa"); // 抛出异常java.lang.UnsupportedOperationException

		list.set(0, "aaa"); // 但是可以改变值

		System.out.println(list.get(0));
		
		/**
		 * 创建不可变的set,不可变的set的集合元素必须要保证唯一性，否则报错
		 */
		System.out.println("---------------不可变Set集合------------");
//		Set<String> of = Set.of("2","1","2"); // duplicate element: 2
		Set<String> of = Set.of("2","1");
		of.forEach(System.out::println);
		
		/**
		 * 不可变的ma集合最多有10个键值对，超过10个的需要使用到ofentries方法实现，传递键值对可变性惨entries(
		 */
		System.out.println("---------------不可变Map集合------------");
		Map<String,String> map = Map.of("张","南京","李","上海","魏","陕西",
				"张1","南京","李1","上海","魏1","陕西",
				"张2","南京","李2","上海","魏2","陕西");
		map.entrySet().forEach(System.out::println);
		System.out.println("---------------------------");
		Set<String> keySet = map.keySet();
		Iterator<String> keyIter = keySet.iterator();
		while (keyIter.hasNext()) {
			String s = (String) keyIter.next();
			System.out.println(map.get(s)+"---"+s+"---");
		}
		System.out.println("---------------------------");
		Map<String, Object> hm = new HashMap<>();
		hm.put("张", "南京");
		hm.put("孙", "北京");
		hm.put("李", "上海");
		hm.put("梁", "咸阳");
		hm.put("文", "吉林");
		hm.put("献", "大连");
		hm.put("王", "西安");
		hm.put("刘", "青岛");
		hm.put("朱", "新疆");
		hm.put("祝", "深圳");
		hm.put("周", "广州");
		// 获取所有的键的对象
		Set<Entry<String, Object>> keySets = hm.entrySet();
		Entry[] array = keySets.toArray(new Map.Entry[0]);
		Map map2 = Map.ofEntries(array);
		map2.entrySet().forEach(System.out::println);
	}

}
